package com.covid.lab3.service;

import com.covid.lab3.model.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DataService implements InitializingBean {
    private static String CORONA_VIRUS_DATA_URL =
            "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private static final List<RegionStats> regionstats = new ArrayList<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }

    //设置更新数据时间
    @Scheduled(cron = "${schedules.updateVirusDataTime}")
    //爬取新冠病毒统计数据的csv文件并解析
    public void fetchCoronaVirusData() throws IOException {
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(CORONA_VIRUS_DATA_URL))
                .header("User-Agent","Mozilla")
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        InputStream inputStream = body.getInputStream();
        Reader reader = new InputStreamReader(inputStream);

        Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(reader);
        int fact = 0;
        for(CSVRecord record : records) {

            if (fact == 0){
                fact = 1;
                continue;
            }

            String state = record.get(0);
            String country = record.get(1);
            int latest = Integer.parseInt(record.get(record.size() - 1));
            int diffFrom = Integer.parseInt(record.get(record.size() - 1))
                    - Integer.parseInt(record.get(record.size() - 2));


            RegionStats re = new RegionStats(state, country, latest, diffFrom);
            regionstats.add(re);
        }
    }

    //返回所有信息
    public static List<RegionStats> getAllRegionStats() {
        return regionstats;
    }



}

